package com.spsy.pay.controller;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class ConcurrentCounter {
    private static final int THREAD_COUNT = 10000;
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    // 使用AtomicInteger保证原子性
    private static AtomicInteger atomicN = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(THREAD_COUNT);

        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.submit(() -> {
                try {
                    atomicN.incrementAndGet(); // 原子操作
                } finally {
                    latch.countDown();
                }
            });
        }

        latch.await(); // 等待所有线程完成
        executor.shutdown();

        System.out.println("Final count: " + atomicN.get()); // 保证是10000
    }
}